#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>

/*
 *  -y:year
 *  -m:month
 *  -d:day
 *  -H:hour
 *  -M:minute
 *  -S:second
 */

#define TIMESTRSIZE 1024
#define FMTSTRSIZE 1024

int main(int argc, char * argv[])
{
	FILE * fp = stdout;
	time_t stamp;
	struct tm * tm;
	char timestr[TIMESTRSIZE];
	char fmtstr[FMTSTRSIZE] = {0};
	int c;

	stamp = time(NULL);
	tm = localtime(&stamp);

	while(1)
	{
		c = getopt(argc, argv, "-H:MSy:md");//!!!!
		if(c < 0)
			break;
		switch(c)
		{
			case 1:
				if(fp == stdout)//only the first dir
				{
					fp = fopen(argv[optind - 1], "w");
					if(fp == NULL)
					{
						perror("fopen");
						fp = stdout;
					}
				}
				break;
			case 'H':
				if(strcmp(optarg,"12") == 0)
					strncat(fmtstr, "%I(%p) ", FMTSTRSIZE - 1);
				else if(strcmp(optarg,"24") == 0)
					strncat(fmtstr, "%H ", FMTSTRSIZE - 1);
				else
					fprintf(stderr, "invalid argument\n");
				break;
			case 'M':
				strncat(fmtstr, "%M ", FMTSTRSIZE - 1);
				break;
			case 'S':
				strncat(fmtstr, "%S ", FMTSTRSIZE - 1);
				break;
			case 'y':
				if(strcmp(optarg,"2") == 0)
					strncat(fmtstr, "%y ", FMTSTRSIZE - 1);
				else if(strcmp(optarg,"4") == 0)
					strncat(fmtstr, "%Y ", FMTSTRSIZE - 1);
				else
					fprintf(stderr, "invalid argument\n");
				break;
			case 'm':
				strncat(fmtstr, "%m ", FMTSTRSIZE - 1);
				break;
			case 'd':
				strncat(fmtstr, "%d ", FMTSTRSIZE - 1);
				break;
			default:
				break;
		}
	}
	strftime(timestr, TIMESTRSIZE, fmtstr, tm);
	strncat(timestr, "\n", TIMESTRSIZE - 1);
	fputs(timestr, fp);

	if(fp != stdout)
		fclose(fp);

	exit(0);
}
